<template>
  <div id="userManagerPage">
    <a-input-search
      style="margin-bottom: 16px"
      v-model:value="search"
      placeholder="输入用户名搜索"
      enter-button="搜索"
      @search="onSearch"
    />
    <a-table :columns="columns" :data-source="data">
      <!-- <template #headerCell="{ column }">
       <template v-if="column.key === 'name'">
         <span>
           <smile-outlined />
           Name
         </span>
       </template>
     </template>-->
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'avatarUrl'">
          <a-image :src="record.avatarUrl" :width="120" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <div v-if="record.userRole === 1">
            <a-tag color="green">管理员</a-tag>
          </div>
          <div v-else>
            <a-tag color="blue">普通用户</a-tag>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          <div>
            {{ dayjs(record.createTime).format("YYYY-MM_DD HH:mm:ss") }}
          </div>
        </template>
        <template v-else-if="column.key === 'name'">
          <a>
            {{ record.name }}
          </a>
        </template>

        <template v-else-if="column.key === 'action'">
          <a-button danger @click="doDelete(record.id)"> 删除</a-button>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { SmileOutlined, DownOutlined } from "@ant-design/icons-vue";
import { deleteUser, searchUsers } from "@/api/user";
import { ref } from "vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";

const search = ref();

const columns = [
  {
    title: "id",
    dataIndex: "id",
  },
  {
    title: "用户名",
    dataIndex: "username",
  },
  {
    title: "账号",
    dataIndex: "userAccount",
  },
  {
    title: "头像",
    dataIndex: "avatarUrl",
  },
  {
    title: "性别",
    dataIndex: "gender",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  {
    title: "用户角色",
    dataIndex: "userRole",
  },
  {
    title: "操作",
    key: "action",
  },
];
//ref设置成响应式变量，想要它去向影响页面的变化或者reactive。ref要变值需要。value，reactive不需要
const data = ref([]);
//获取数据
const fetchData = async (username = "") => {
  const res = await searchUsers(username);
  if (res.data.data) {
    data.value = res.data.data;
  } else {
    message.error("获取数据失败");
  }
};
//竟然可以自己内部调用
fetchData();
//按用户名搜索
const onSearch = () => {
  fetchData(search.value);
};
const doDelete = async (id: string) => {
  if (!id) return;
  const res = await deleteUser(id);
  if (res.data.code === 200) {
    message.success("删除成功");
    fetchData();
  } else {
    message.error("删除失败");
  }
};
</script>
